package com.mavenq.fly.utils.excelv3;

/**
 * Excel 导入异常（包含行列信息）
 */
public class ExcelImportException extends RuntimeException {
    private final int rowIndex;
    private final int columnIndex;
    private final String sheetName;
    private final String fieldName;
    private final Object cellValue;

    public ExcelImportException(String message, int rowIndex, int columnIndex,
                                String sheetName, String fieldName, Object cellValue) {
        super(message);
        this.rowIndex = rowIndex;
        this.columnIndex = columnIndex;
        this.sheetName = sheetName;
        this.fieldName = fieldName;
        this.cellValue = cellValue;
    }

    public ExcelImportException(String message, int rowIndex, int columnIndex,
                                String sheetName, String fieldName, Object cellValue, Throwable cause) {
        super(message, cause);
        this.rowIndex = rowIndex;
        this.columnIndex = columnIndex;
        this.sheetName = sheetName;
        this.fieldName = fieldName;
        this.cellValue = cellValue;
    }

    // Getter 方法
    public int getRowIndex() {
        return rowIndex;
    }

    public int getColumnIndex() {
        return columnIndex;
    }

    public String getSheetName() {
        return sheetName;
    }

    public String getFieldName() {
        return fieldName;
    }

    public Object getCellValue() {
        return cellValue;
    }

    /**
     * 获取用户友好的错误位置信息（Excel行列号，从1开始）
     */
    public String getPositionInfo() {
        int excelRow = rowIndex + 1; // Excel行号从1开始
        String excelColumn = toExcelColumnName(columnIndex); // Excel列号A,B,C...
        return String.format("Sheet[%s] 第%d行第%s列",
                sheetName, excelRow, excelColumn);
    }

    /**
     * 获取完整的错误信息
     */
    public String getFullErrorMessage() {
        return String.format("%s, 字段: %s, 值: %s",
                getPositionInfo(), fieldName,
                cellValue != null ? cellValue.toString() : "空值");
    }

    /**
     * 将列索引转换为Excel列名 (0->A, 1->B, 26->AA, ...)
     */
    private static String toExcelColumnName(int columnIndex) {
        StringBuilder sb = new StringBuilder();
        while (columnIndex >= 0) {
            sb.append((char) ('A' + (columnIndex % 26)));
            columnIndex = (columnIndex / 26) - 1;
        }
        return sb.reverse().toString();
    }
}